package com.hqw.mindanews;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.push.BmobPush;
import cn.bmob.v3.BmobObject;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.SaveListener;
import cn.pedant.SweetAlert.SweetAlertDialog;

import com.bmob.BmobProFile;
import com.bmob.btp.callback.UploadBatchListener;
import com.hqw.mindanews.application.SysApplication;
import com.hqw.mindanews.bean.NewsMsg;
import com.hqw.mindanews.bean.User;
import com.hqw.mindanews.utils.Bimp;
import com.hqw.mindanews.utils.Constant;
import com.hqw.mindanews.utils.FileUtils;
import com.hqw.mindanews.view.SegmentButton;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class PublishedActivity extends Activity {

	private GridView noScrollgridview;
	private GridAdapter adapter;
	private TextView activity_selectimg_send;
	private SegmentButton segment_button;
	private Integer mChannel = 0;
	private EditText mContent;
	private static String photoPath = "/sdcard/mindanews/";
	private TextView mBackToMain;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_selectimg);
		processExtraData();
		Init();
		SysApplication.getInstance().addActivity(this);
	}

	// 2015-02-04 Renzhenwen 
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.e("", "按下了退出");
		// 按两下退出程序
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Bimp.drr.clear();
			Bimp.bmp.clear();
			Bimp.max = 0;
			// super.onDestroy();
			FileUtils.deleteDir();
			//finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void Init() {
		mBackToMain = (TextView) findViewById(R.id.pubilish_back);
		mBackToMain.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent it = new Intent(
						PublishedActivity.this,
						MainActivity.class);
				startActivity(it);
				
			}
		});
		mContent = (EditText) findViewById(R.id.msg_content_text);
		segment_button = (SegmentButton) findViewById(R.id.segment_button);
		segment_button
				.setOnCheckedChangeListener(new SegmentButton.OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(int position, Button button) {
						mChannel = position;
					}
				});
		noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
		noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
		adapter = new GridAdapter(this);
		adapter.update();
		noScrollgridview.setAdapter(adapter);
		noScrollgridview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == Bimp.bmp.size()) {
					new PopupWindows(PublishedActivity.this, noScrollgridview);
				} else {
					Intent intent = new Intent(PublishedActivity.this,
							PhotoActivity.class);
					intent.putExtra("ID", arg2);
					startActivity(intent);
				}
			}
		});
		activity_selectimg_send = (TextView) findViewById(R.id.activity_selectimg_send);
		activity_selectimg_send.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				List<String> list = new ArrayList<String>();
				for (int i = 0; i < Bimp.drr.size(); i++) {
					String Str = Bimp.drr.get(i).substring(
							Bimp.drr.get(i).lastIndexOf("/") + 1,
							Bimp.drr.get(i).lastIndexOf("."));
					list.add(FileUtils.SDPATH + Str + ".JPEG");
				}
				// 高清的压缩图片全部就在 list 路径里面了
				// 高清的压缩过的 bmp 对象 都在 Bimp.bmp里面
				// 完成上传服务器后 .........
				UploadPic(list);

			}

			private void UploadPic(List<String> list) {
				String[] picArray = new String[list.size()];
				for (int i = 0; i < list.size(); i++) {
					picArray[i] = list.get(i);
					Log.i("bmob", "文件地址：" + list.get(i));
				}
				final ProgressDialog postProgress = new ProgressDialog(
						PublishedActivity.this);
				postProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				postProgress.setIndeterminate(false);
				postProgress.show();
				BmobProFile.getInstance(PublishedActivity.this).uploadBatch(
						picArray, new UploadBatchListener() {

							@Override
							public void onError(int statuscode, String errormsg) {
								Log.i("bmob", "批量上传出错：" + statuscode + "--"
										+ errormsg);
							}

							@Override
							public void onSuccess(boolean isFinish,
									String[] fileNames, String[] urls,
									BmobFile[] files) {
								// isFinish ：批量上传是否完成
								// fileNames：文件名数组
								// urls : url：文件地址数组
								// files :
								// BmobFile文件数组，`V3.4.1版本`开始提供，用于兼容新旧文件服务
								if (isFinish) {
									saveUserMsg(fileNames, files);
								}
							}

							private void saveUserMsg(String[] fileNames,
									BmobFile[] files) {
								List<String> fileNamesList = new ArrayList<String>();
								List<BmobFile> filesList = new ArrayList<BmobFile>();
								User currentUser = BmobUser.getCurrentUser(
										PublishedActivity.this, User.class);

								String content = mContent.getText().toString();
								for (int i = 0; i < files.length; i++) {
									fileNamesList.add(fileNames[i]);
									filesList.add(files[i]);
								}

								NewsMsg newsMsg = new NewsMsg();
								newsMsg.setUser(currentUser);
								newsMsg.setFileNames(fileNamesList);
								newsMsg.setBmobFiles(filesList);
								newsMsg.setContent(content);
								newsMsg.setChannel(mChannel);
								newsMsg.setType(Constant.isChecking);
								newsMsg.setFeedBack("yes");

								newsMsg.save(PublishedActivity.this,
										new SaveListener() {

											@Override
											public void onSuccess() {
												FileUtils.deleteDir();
												Bimp.drr.clear();
												Bimp.bmp.clear();
												Bimp.max = 0;
												PublishedActivity.this.finish();

												Intent it = new Intent(
														PublishedActivity.this,
														MainActivity.class);
												startActivity(it);
											}

											@Override
											public void onFailure(int arg0,
													String arg1) {

											}
										});
							}

							@Override
							public void onProgress(int curIndex,
									int curPercent, int total, int totalPercent) {
								postProgress.setMax(totalPercent);
								postProgress.setProgress((int) curPercent);

							}
						});

			}
		});
	}

	@SuppressLint("HandlerLeak")
	public class GridAdapter extends BaseAdapter {
		private LayoutInflater inflater; // 视图容器
		private int selectedPosition = -1;// 选中的位置
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public void update() {
			loading();
		}

		public int getCount() {
			return (Bimp.bmp.size() + 1);
		}

		public Object getItem(int arg0) {

			return null;
		}

		public long getItemId(int arg0) {

			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		/**
		 * ListView Item设置
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			final int coord = position;
			ViewHolder holder = null;
			if (convertView == null) {

				convertView = inflater.inflate(R.layout.item_published_grida,
						parent, false);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.item_grida_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (position == Bimp.bmp.size()) {
				holder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.icon_addpic_unfocused));
				if (position == 9) {
					holder.image.setVisibility(View.GONE);
				}
			} else {
				holder.image.setImageBitmap(Bimp.bmp.get(position));
			}

			return convertView;
		}

		public class ViewHolder {
			public ImageView image;
		}

		Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					adapter.notifyDataSetChanged();
					break;
				}
				super.handleMessage(msg);
			}
		};

		public void loading() {
			Log.i("bmob", "进来了");
			new Thread(new Runnable() {
				public void run() {
					while (true) {
						Log.i("bmob", "进来了222");
						if (Bimp.max == Bimp.drr.size()) {
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
							break;
						} else {
							try {
								Log.i("bmob", "进来了11111");
								String path = Bimp.drr.get(Bimp.max);
								Log.i("bmob", "path==  "+path);
								Bitmap bm = Bimp.revitionImageSize(path);
								Bimp.bmp.add(bm);
								String newStr = path.substring(
										path.lastIndexOf("/") + 1,
										path.lastIndexOf("."));
								FileUtils.saveBitmap(bm, "" + newStr);
								Bimp.max += 1;
								Message message = new Message();
								message.what = 1;
								handler.sendMessage(message);
							} catch (IOException e) {

								e.printStackTrace();
							}
						}
					}
				}
			}).start();
		}
	}

	public String getString(String s) {
		String path = null;
		if (s == null)
			return "";
		for (int i = s.length() - 1; i > 0; i++) {
			s.charAt(i);
		}
		return path;
	}

	protected void onRestart() {
		adapter.update();
		super.onRestart();
	}

	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, View parent) {

			View view = View
					.inflate(mContext, R.layout.item_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);
			update();

			Button bt1 = (Button) view
					.findViewById(R.id.item_popupwindows_camera);
			Button bt2 = (Button) view
					.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view
					.findViewById(R.id.item_popupwindows_cancel);
			bt1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					photo();
					dismiss();
				}
			});
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(PublishedActivity.this,
							TestPicActivity.class);

					startActivity(intent);
					dismiss();
				}
			});
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});

		}
	}

	@Override
	protected void onDestroy() {

		super.onDestroy();
		Log.i("bmob", "被销毁了");
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		setIntent(intent);
		processExtraData();
	}

	private void processExtraData() {
		// TODO Auto-generated method stub
		Intent intent = getIntent();
	}

	private static final int TAKE_PICTURE = 0x000000;
	private String path = "";

	public void photo() {
		// Intent openCameraIntent = new
		// Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		// File file = new File(Environment.getExternalStorageDirectory()
		// + "/myimage/", String.valueOf(System.currentTimeMillis())
		// + ".jpg");
		// path = file.getPath();
		// Uri imageUri = Uri.fromFile(file);
		// openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		// startActivityForResult(openCameraIntent, TAKE_PICTURE);

		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		File file = new File(photoPath);
		if (!file.exists()) { // 检查图片存放的文件夹是否存在
			file.mkdir(); // 不存在的话 创建文件夹
		}
		File photo = new File(photoPath
				+ String.valueOf(System.currentTimeMillis()) + ".jpg");
		path = photo.getPath();
		Uri imageUri = Uri.fromFile(photo);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		startActivityForResult(intent, TAKE_PICTURE);

		// Intent i = new Intent(
		// MediaStore.ACTION_IMAGE_CAPTURE);
		// startActivityForResult(i, 0);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		Log.i("bmob", "返回的code" + resultCode);
		Bimp.drr.add(path);
		Log.i("bmob", "获取的长度  " + Bimp.drr.size());
//		switch (requestCode) {
//
//		case -1:
//			if (Bimp.drr.size() < 9 && resultCode == -1) {
//
//			}
//			break;
//		}

	}

	 

}
